package com.jp.knowledge.util;

import android.graphics.Bitmap;

import com.google.zxing.BarcodeFormat;
import com.google.zxing.MultiFormatWriter;
import com.google.zxing.WriterException;
import com.google.zxing.common.BitMatrix;

import rx.Observable;
import rx.Observer;
import rx.Subscriber;
import rx.android.schedulers.AndroidSchedulers;
import rx.schedulers.Schedulers;

/**
 * Created by 528787067@qq.com on 2017/7/6.
 */

public class QRCodeUtils {

	public static Bitmap encodeAsBitmap(String url){
		return encodeAsBitmap(url, 300);
	}

	public static Bitmap encodeAsBitmap(String url, int side){
		return encodeAsBitmap(url, side, side);
	}

	public static Bitmap encodeAsBitmap(String url, int width, int height){
		BitMatrix matrix = null;
		try {
			matrix = new MultiFormatWriter().encode(url, BarcodeFormat.QR_CODE, width, height);
		} catch (WriterException e) {
			return null;
		}
		int w = matrix.getWidth();
		int h = matrix.getHeight();
		int[] pixels = new int[w * h];
		for (int y = 0; y < h; y++) {
			for (int x = 0; x < w; x++) {
				if (matrix.get(x, y)) {
					pixels[y * w + x] = 0xff000000;
				}
			}
		}
		Bitmap bitmap = Bitmap.createBitmap(w, h, Bitmap.Config.ARGB_8888);
		bitmap.setPixels(pixels, 0, w, 0, 0, w, h);
		return bitmap;
	}

	public static void encodeAsBitmap(String url, EncodeListener encodeListener){
		encodeAsBitmap(url, 300, encodeListener);
	}

	public static void encodeAsBitmap(String url, int side, EncodeListener encodeListener){
		encodeAsBitmap(url, side, side, encodeListener);
	}

	public static void encodeAsBitmap(final String url, final int width, final int height, final EncodeListener encodeListener){
		Observable.create(new Observable.OnSubscribe<Bitmap>() {
			@Override
			public void call(Subscriber<? super Bitmap> subscriber) {
				Bitmap bitmap = encodeAsBitmap(url, width, height);
				subscriber.onNext(bitmap);
			}
		}).subscribeOn(Schedulers.io())
		.observeOn(AndroidSchedulers.mainThread())
		.subscribe(new Observer<Bitmap>() {
			@Override
			public void onCompleted() {}
			@Override
			public void onError(Throwable e) {
				if(encodeListener != null)
					encodeListener.encodeError(e);
			}
			@Override
			public void onNext(Bitmap bitmap) {
				if(encodeListener != null)
					encodeListener.encodeSuccedd(bitmap);
			}
		});
	}

	public interface EncodeListener{
		void encodeSuccedd(Bitmap qrCode);
		void encodeError(Throwable e);
	}
}
